﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LX.Core.Auth;
using LX.Data;
using LX.Web.Auth;

namespace LX.Flower.Data.Managers
{
    public class CookiePrincipalManager<T> : IAuthTicketManager<T> where T : class, IPrincipal,IEntity
    {
        public IPersistentContext Repository { get; set; }
        private CookiePersistentProvider cookieprovider;
        private T principal;
        public CookiePrincipalManager(IPersistentContext repository)
        {
            cookieprovider = new CookiePersistentProvider(typeof(T).ToString());
            Repository = repository;
        }

        public bool IsLogined()
        {
            return GetCurrentPrincipal() != null;
        }

        public IPrincipal GetPrincipal()
        {
            T admin = GetCurrentPrincipal();
            if (admin == null)
            {
                return Principal.Anonymous;
            }
            return admin;
        }

        public T GetCurrentPrincipal()
        {
            if (principal == null)
            {
                var id = cookieprovider.GetPrincipalId();
                if (string.IsNullOrWhiteSpace(id)) return null;
                string[] tids = id.Split(':');
                if (tids.Length != 2) return null;
                int intid;
                if (int.TryParse(tids[tids.Length - 1], out intid))
                {
                    principal = Repository.Get<T>(intid);
                }
            }
            return principal;
        }

        public void SetCurrentPrincipal(T principal, TicketPersistentOption option)
        {
            if (principal == null)
            {
                if (this.principal != null)
                {
                    cookieprovider.Clear(this.principal.GetId());
                }
            }
            else
            {
                cookieprovider.Save(principal.GetId(), option);

            }
            this.principal = principal;
        }
    }
}
